package cn.le.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.*;

public class ProxyHttpUtil {

    public static String get(String url){
        BufferedReader in = null;
        String result = "";
        while (true){
            Proxy proxy = IpProxyPool.getProxy();
            InputStream inputStream = conn(url,proxy);
            if (inputStream == null){
                //移除没用的
                IpProxyPool.remove(proxy);
                continue;
            }
            in = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            try {
                while ((line = in.readLine()) != null) {
                    result += line;
                }
            }catch (IOException e){
                e.printStackTrace();
            }
            //保留已成功的
            IpProxyPool.retain(proxy);
            break;
        }
        return result;
    }

    private static InputStream conn(String url,Proxy proxy){
        try {
            URLConnection httpCon = new URL(url).openConnection(proxy);
            httpCon.setConnectTimeout(5000);
            httpCon.setReadTimeout(5000);
            int code = ((HttpURLConnection) httpCon).getResponseCode();
            if (code != 200){
                return null;
            }
            httpCon.connect();
            System.out.println("成功---->" + proxy.address());
            return httpCon.getInputStream();
        } catch (Exception e) {
        }
        return null;
    }
}
